import * as React from 'react';
//建立页面数据和store 的关联
import { connect } from 'react-redux'
import axios from 'axios';
import { Post, Get, Patch, Put } from '../../utils/utilHttp'
import { Link, RouteComponentProps } from 'react-router-dom';
import { Button, WhiteSpace, WingBlank, Icon } from 'antd-mobile';
import './home.scss'

import  img001 from './img/001.jpg'
import  img002 from './img/002.jpg'
import  img003 from './img/003.jpg'

interface IState {
  map:Eve,//地图实例
  BMap:Eve,//地图类
  isRun:boolean,//中间图标运动
  showRun:boolean,//显示中间的图标
  nowCity:string,//当前城市
  nowLocal:string,//当前位置
  nowStartInput:boolean,//当前是出发地的输入框
  startLocal:string,//出发地
  endLocal:string,//目的地
  centerLng:string,//中心位置的东经北纬
  centerLat:string,
  nowLng:string,//当前的东经北纬
  nowLat:string,
  endLng:string,//目的地东经北纬
  endLat:string,
  carList:string[],
  carActiveIndex:number,//选中的下标
  isNowTime:boolean,//是否当前用车
  aboutLocal:{name:string,add:string}[],
  showAboutLocal:boolean
}
interface IProps extends RouteComponentProps {
}
interface Eve {
  Point?:any,
  [k:string]:any
}
class Home extends React.Component<IProps, IState> {
  state:IState = {
    map:{},//地图实例
    BMap:{},//地图类
    isRun:false,//中间图标运动
    showRun:false,//显示中间的图标
    nowCity:'',//当前城市
    nowLocal:'',//当前位置
    nowStartInput:true,//当前是出发地的输入框
    startLocal:'',//出发地
    endLocal:'',//目的地
    centerLng:'',//中心位置的东经北纬
    centerLat:'',
    nowLng:'',//当前的东经北纬
    nowLat:'',
    endLng:'',//目的地东经北纬
    endLat:'',
    carList:['公交','顺风车','快车','出租车','专车'],
    carActiveIndex:0,//选中的下标
    isNowTime:true,//是否当前用车
    aboutLocal:[{name:'',add:''}],//目的地相关地址推荐
    showAboutLocal:false,//显示目的地相关地址页面
  }
  componentDidMount() {
    this.initMap(); 
  }
  componentDidUpdate(prevProps:any, prevState:any){
    //监听当前是否登录 控制显示
    // if ((this.props as any).isLogin !== (prevProps as any).isLogin) {
    //   if((this.props as any).isLogin){
    //     this.setState({
    //       isLogin:(this.props as any).isLogin,
    //       userInfo:(this.props as any).userInfo
    //     })
    //   }
    // }
  }
  //封装ajax
  axiosJsonp = (url:string):any => {
    return new Promise((resolve, reject) => {
        let JSONP = document.createElement("script");
        JSONP.type = "text/javascript";
        JSONP.src = `${url}`;
        document.getElementsByTagName("head")[0].appendChild(JSONP);

        (window as any).callback = (res:any) => {
            resolve(res)
        }
        setTimeout(() => {
            document.getElementsByTagName("head")[0].removeChild(JSONP)
        }, 5000)
    })
  }
  //初始化
  initMap=()=>{
    let BMap =window.BMap;
    let map = new BMap.Map("container"); // 创建Map实例
    let point = null;//坐标点
    //进来就先定位
    //定位
    var geolocation = new BMap.Geolocation();
    geolocation.getCurrentPosition((r:any)=>{
      //初始化地图
      console.log('当前经纬度：'+r.point.lng,r.point.lat);
      point = new BMap.Point(r.point.lng,r.point.lat);
      map.centerAndZoom(point, 18); // 初始化地图,设置中心点坐标和地图级别
      map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放

      map.addControl(new BMap.NavigationControl());    
      map.addControl(new BMap.ScaleControl());    
      map.addControl(new BMap.OverviewMapControl());    
      // map.addControl(new BMap.MapTypeControl());    
      

      if(geolocation.getStatus() == "0"){
        //已经获得经纬度
        // alert('您的位置：'+r.point.lng+','+r.point.lat);

        //经纬度转地址
        var myGeo = new window.BMap.Geocoder();  
        // 根据坐标得到地址描述    
        myGeo.getLocation(new window.BMap.Point(r.point.lng, r.point.lat),(result:any)=>{      
          if (result){     
            console.log(result); 
            console.log(result.address); 
            console.log(result.addressComponents.city);
            let nowCity=result.addressComponents&&result.addressComponents.city;
            //得到城市设置城市
            map.setCurrentCity(nowCity); // 仅当设置城市信息时，MapTypeControl的切换功能才能可用
            this.setState({
              nowCity,
              startLocal:result.address,
              nowLng:r.point.lng,
              nowLat:r.point.lat
            },()=>{
              setTimeout(() => {
                console.log('添加消息提示')
              }, 1000);
            })
          }      
        });

        //调接口获取精确经纬度(好像没什么卵用)
        // this.axiosJsonp(`http://api.map.baidu.com/reverse_geocoding/v3/?ak=2Ro4FB4Y8c8od4iHlaGGLWxTiDHfQHZY&output=json&coordtype=wgs84ll&location=${r.point.lat},${r.point.lng}&callback=callback`)
        // .then((res:any)=>{
        //   let resObj=res;
        //   // console.log(resObj);
        //   if(resObj.status==0){
        //     // alert(resObj.result.formatted_address)
        //     // alert(resObj.result.location.lng)
        //     setTimeout(() => {
        //       let point = new BMap.Point(resObj.result.location.lng,resObj.result.location.lat)
        //       let marker = new BMap.Marker(point);        // 创建标注    
        //       map.addOverlay(marker);                     // 将标注添加到地图中 
        //     }, 5000);
        //   }
        // })
      } else {
        console.log('failed'+geolocation.getStatus());
      }        
    });

    
    // var marker = new BMap.Marker(point);        // 创建标注    
    // map.addOverlay(marker);                     // 将标注添加到地图中 

    //点击了标注,添加一个标注
    // marker.addEventListener("click", function(){    
    //   console.log("您点击了标注,添加一个标注");   
    //   var myIcon = new BMap.Icon("markers.png", 
    //   new BMap.Size(23, 25), {
    //     offset: new BMap.Size(10, 25), // 指定定位位置
    //     imageOffset: new BMap.Size(0, 0 - 10 * 25) // 设置图片偏移
    //   });
    // }); 

    //地图拖拽事件
    //dragstart  dragging  dragend
    map.addEventListener("dragstart",()=>{
      this.setState({
        isRun:false
      })
    })
    map.addEventListener("dragging",()=>{
      (!this.state.showRun)&&this.setState({
        showRun:true
      })
    })
    map.addEventListener("dragend",()=>{
      var bs = map.getBounds();   //获取可视区域
      var bssw = bs.getSouthWest();   //可视区域左下角
      var bsne = bs.getNorthEast();   //可视区域右上角
      console.log("当前地图可视范围是：" + bssw.lng + "," + bssw.lat + "到" + bsne.lng + "," + bsne.lat);
      //计算得到中心点经纬度
      let centerLng= ((bssw.lng*1000000+ bsne.lng*1000000)/1000000/2).toFixed(6);
      let centerLat= ((bssw.lat*1000000+ bsne.lat*1000000)/1000000/2).toFixed(6);
      console.log('当前中心的经纬度：'+centerLng,centerLat);

      //经纬度转地址
      var myGeo = new BMap.Geocoder();  
      // 根据坐标得到地址描述    
      myGeo.getLocation(new BMap.Point(centerLng, centerLat),(result:any)=>{      
        if (result){     
          console.log(result); 
          console.log(result.address); 
          this.setState({
            isRun:true,
            nowLocal:result.surroundingPois[0]&&result.surroundingPois[0].title,
            startLocal:result.surroundingPois[0]&&result.surroundingPois[0].title,
            centerLng,
            centerLat,
            nowLng:centerLat,
            nowLat:centerLat
          })
        }      
      });
    })
    
    //添加消息提示框
    // var opts = {    
    //   width : 250,     // 信息窗口宽度    
    //   height: 100,     // 信息窗口高度    
    //   title : "提示标题"  // 信息窗口标题   
    // }    
    // var infoWindow = new BMap.InfoWindow("提示内容", opts);  // 创建信息窗口对象    
    // map.openInfoWindow(infoWindow, point);      // 打开信息窗口 指向谁
    
    //新增一个地图图层
    var traffic = new BMap.TrafficLayer();        // 创建交通流量图层实例      
    map.addTileLayer(traffic);                    // 将图层添加到地图上

    this.setState({
      map,
      BMap
    })
  

    // setTimeout(() => {
    //   driving.search(start, end);
    // }, 5000);

    //添加全景功能
    // var stCtrl = new BMap.PanoramaControl();  
    // stCtrl.setOffset(new BMap.Size(20, 20));  
    // map.addControl(stCtrl);    
  }
  //选择不同的车
  carActive=(index:number):void=>{
    this.setState({
      carActiveIndex:index
    })
  }
  //用户输入
  userImport=(e:Eve,type:string):void=>{
    let data:any={};
    data[type]=e.target.value;
    this.setState(data);
  }
  //点击打开 相关目的地页面
  openAboutLocal=(type:string)=>{
    let nowStartInput=(type=='start');
    this.setState({
      showAboutLocal:true,
      nowStartInput,
      aboutLocal:[{name:'',add:''}]
    },()=>{
      //如果是点击 起始地址
      if(nowStartInput){
        this.getAboutLocal('');
      }
    })
  }
  //关闭菜单
  closeMenu=()=>{
    this.setState({
      showAboutLocal:false
    })
  }
  //地址点击
  clickLocal=(item:{name:string,add:string}) => {
    let _this=this;
    let {BMap,map,nowCity,nowStartInput,nowLng,nowLat} =this.state;
    // 创建地址解析器实例     
    var myGeo = new BMap.Geocoder();      
    // 将地址解析结果显示在地图上，并调整地图视野    
    myGeo.getPoint(item.add, function(point:{lng:string,lat:string}){
        if (point) {
          //如果是起始地
          if(nowStartInput){
            map.centerAndZoom(point, 17);      
            map.addOverlay(new BMap.Marker(point));
            _this.setState({
              nowLng:point.lng,
              nowLat:point.lat,
              startLocal:item.name,
              showAboutLocal:false
            })      
          }else{
            //规划路线 走起
            _this.setState({
              endLng:point.lng,
              endLat:point.lat,
              endLocal:item.name,
              showAboutLocal:false,
              showRun:false
            },()=>{
              //路线规划
              var driving = new BMap.DrivingRoute(map, { 
                renderOptions: { 
                  map: map, 
                  autoViewport: true 
                } 
              });
              var start = new BMap.Point(nowLng,nowLat);
              var end = new BMap.Point(point.lng,point.lat);
              driving.search(start, end);
            })  
          }      
        }      
    }, nowCity);
  }
  //输入目的地 得到相关推荐的地址 ，准确指出是哪一个
  getAboutLocal=(e:any)=>{
    let {showAboutLocal,startLocal,endLocal,nowCity,map,nowLng,nowLat} =this.state;
    let BMap:Eve =this.state.BMap;
    let _this=this;
    let value = e==''?'':e.target.value;

    //根据名称获取相关地址
    let getAbout =(add:string) => {
      var options = {      
        onSearchComplete: function(results:any){      
          if (local.getStatus() == "0"){      
            // 判断状态是否正确      
            var aboutLocal = [];      
            for (var i = 0; i < results.getCurrentNumPois(); i ++){      
              aboutLocal.push({name:results.getPoi(i).title,add:results.getPoi(i).address});      
            }
            console.log(aboutLocal);
            _this.setState({
              aboutLocal
            })
          }      
        }      
      };      
      var local = new BMap.LocalSearch(map, options);      
      local.search(add);
    }

    //如果输入的是起始位置
    if(showAboutLocal){
      //起始位置进来 就显示当前定位的相关地址
      if(value===''){
        getAbout(startLocal);
      }else{
        getAbout(value);
      }
    }else{
      getAbout(value);
    }
  }
  //是否现在叫车
  changeRunTime=(type:boolean)=>{
    this.setState({
      isNowTime:type
    })
  }

  render() {
    let { isRun,showRun,nowCity,carList,carActiveIndex,nowLocal,endLocal,startLocal,isNowTime,showAboutLocal,aboutLocal }=this.state;
    return (
      <div className='home_box'>
        <div className='home_top'>
          <div className='top_nav font_22'>
            <i className='icon icon_wodejuhuasuan'></i>
            <div>
              <i className='icon icon_wxbdingwei'></i>
              <span>{nowCity||'中国'}</span>
            </div>
            <i className='icon icon_xiaoxizhongxin'></i>
          </div>
          <div className='top_title'>
            {carList.map((item:string,index:number)=>{
              return (<span className={carActiveIndex==index?'active':''} key={index} onClick={()=>{this.carActive(index);}}>{item}</span>)
            })}
          </div>
        </div>
        <div className='home_main' style={{position: 'fixed',top: '1rem',left: 0,right: 0,bottom: 0}}>
          <div className='container' id='container'></div>
          {showRun&&<div className='center_icon_box'>
            <i className={`icon icon_wxbdingwei center_icon ${isRun?'run':''}`}></i>
          </div>}
        </div>
        <div className='home_bottom'>
          <div className='bottom_top'>
            <div className={`top_icon ${isNowTime?'active':''}`} onClick={()=>{this.changeRunTime(true)}}>现在</div>
            <div className={`top_icon ${!isNowTime?'active':''}`} onClick={()=>{this.changeRunTime(false)}}>预约</div>
          </div>
          <div className='pad_l_30 pad_r_30'>
            <div className='start'>
              <span>出发地&nbsp;：</span>
              <div className='color_999' onClick={()=>{this.openAboutLocal('start')}}>{startLocal}</div>
            </div>
            <div className='border_middle'></div>
            <div className='end'>
              <span>目的地&nbsp;：</span>
              <div className='color_999' onClick={()=>{this.openAboutLocal('end')}} >{endLocal||'您要去哪儿'}</div>
            </div>
            <div className='border_middle'></div>
          </div>
        </div>
        <div className={`about_local_box ${showAboutLocal?'on':'off'}`}>
          <div className='about_top'>
            <div className='about_top_l'>上海<i className='icon icon_xiala'></i></div>
            <input type='text' placeholder='您要去哪里儿' onChange={(e)=>{this.getAboutLocal(e)}}  onBlur={(e)=>{this.getAboutLocal(e)}}/>
            <div className='about_top_r' onClick={()=>{this.closeMenu()}}>取消</div>
          </div>
          <div className='munu_item_box'>
            <div className='munu_item'>
              <ul>
                {
                  aboutLocal.map((item:{name:string,add:string},index:number)=>{
                    if(item.name){
                      return(<li className='item_li' key={index} onClick={()=>{this.clickLocal(item)}}>
                        <i className='icon icon_shijian'></i>
                        <div>
                          <div className='item_name font_34'>{item.name}</div>
                          <div className='item_add  font_24'>{item.add}</div>
                        </div>
                      </li>)
                    }
                  })
                }
              </ul>
            </div>
          </div>
        </div>
      </div>
    )
  }
}


//将store里面的数据映射到props 这个数据
//就是取store的数据 然后操作 赋值给页面的变量
//将页面数据和全局数据绑定
const mapState = ({ store }: any) => {
  return ({
    isLogin: store.isLogin,
    userInfo:store.userInfo
  })
}

const mapDispatch = ({ store }: any) => ({
  // changeLoaderType() {
  //   store.changeLoaderType(true)
  // }
  setPlayListAct(data:any){
    store.setPlayListAct(data)
  },
  setMp3ListAct(data:any){
    store.setMp3ListFun(data)
  },
})
//返回了 connect 其实是一个容器组件
export default connect(mapState, mapDispatch)(Home); 
